package com.wzq.solution;

import java.util.*;

class Solution47 {


    /***********递归法 **/


    public static List<List<Integer>> permuteUnique(int[] nums){

        List<List<Integer>> rst = new ArrayList<List<Integer>>();
        permute2(nums,0,rst);
        return rst;
    }

    public static void permute2(int[] nums,int k,List<List<Integer>> rst){

        if (k == nums.length-1){
            rst.add(arrToList(nums));
        }else{
            Set<Integer> set = new HashSet<Integer>();
            for (int i=k;i<nums.length;i++){
                if(!set.contains(nums[i])){
                    swap(nums,i,k);
                    permute2(nums,k+1,rst);
                    swap(nums,i,k);
                    set.add(nums[i]);
                }
            }
        }
    }

    private static List<Integer> arrToList(int[] nums){
        List<Integer> l = new ArrayList<Integer>(nums.length);
        for (int n:nums){
            l.add(n);
        }
        return l;
    }

    private static void swap(int[] arr,int i,int j){
        if(i != j){
            arr[i] = arr[i]^arr[j];
            arr[j] = arr[i]^arr[j];
            arr[i] = arr[i]^arr[j];
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> l = permuteUnique(new int[]{1,3, 2});
        System.out.println(l);

    }

}